package ex01;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by lili on 2017/8/7
 */
public class Request {

    private InputStream input;
    private String uri;

    public Request(InputStream input) {
        this.input = input;
    }

    //解析http请求
    public void parse(){
        //2048字节
        StringBuffer request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];
        try {
            //input读入buffer
            i = input.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            i = -1;
        }

        for (int j = 0; j < i; j++) {
            request.append((char)buffer[j]);
        }

        System.out.println("------Request------");
        System.out.println(request.toString());
        //CLRF  解析URL   in ->out   
        uri = parseUri(request.toString());

    }

    /**
     * GET /index.html HTTP/1.1  == >   /index.html
     * @param requestString
     * @return
     */
    private String parseUri(String requestString){

        //解析出URI
        int index1,index2;
        index1 = requestString.indexOf(' ');
        if(index1!=-1){
            index2 = requestString.indexOf(' ', index1 + 1);
            if(index2 > index1){
                return requestString.substring(index1+1,index2);
            }
        }
        return null;
    }

    public String getUri(){
        return uri;
    }


}
